package com.shareyi.baseproject.kernel.adapter.spi.lock;

import com.shareyi.baseproject.kernel.common.exception.LockException;
import com.shareyi.baseproject.kernel.common.spi.cache.CacheService;
import com.shareyi.baseproject.kernel.common.spi.lock.DistributedLock;
import com.shareyi.baseproject.kernel.common.utils.MyStringUtils;
import lombok.Setter;

import java.util.Optional;
import java.util.concurrent.TimeUnit;

/**
 * 默认基于缓存的分布式锁执行器
 *
 * @author david
 * @date 2021-09-01
 */
@Setter
public class DefaultCacheDistributedLock implements DistributedLock {

    /**
     * 缓存服务
     */
    private CacheService cacheService;

    @Override
    public Optional<String> tryLock(String key, long timeoutSec) throws LockException {
        return this.tryLock(key, MyStringUtils.generateUUID(), timeoutSec);
    }

    @Override
    public Optional<String> tryLock(String key, String uuid, long timeoutSec) throws LockException {
        boolean success = cacheService.setIfNotExist(key, uuid, timeoutSec, TimeUnit.SECONDS);
        return success ? Optional.of(uuid) : Optional.empty();
    }

    @Override
    public boolean unlock(String key, String lockId) throws LockException {
        return cacheService.equalThenDelete(key, lockId);
    }
}
